package com.csun.nusing.ui.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.csun.nusing.R;
import com.csun.nusing.presenter.SuiFangDevicePresenter;
import com.csun.nusing.presenter.inter.IBase;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.util.ToastUtil;
import com.linktop.whealthService.HealthApi;
import com.linktop.whealthService.HealthApi.BleCallBack;
import com.linktop.whealthService.HealthApi.EcgCallBack;
import com.linktop.whealthService.HealthApi.HealthApiCallBack;
import com.linktop.whealthService.OnBLEService;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 随访仪的主界面 ClassName: SuiFangDeviceActivity
 * 
 * @Description: 随访仪设备操作界面
 * @author fzq
 * @date 2017-10-24
 */
public class SuiFangDeviceActivity extends BaseActivity<SuiFangDevicePresenter>
		implements IBase {

	/**
	 * 控件
	 */
	private ImageView oldertest_search_iv;
	private LinearLayout oldertest_bloodpress_ll;
	private LinearLayout oldertest_temperature_ll;
	private LinearLayout oldertest_bloodoxy_ll;
	private LinearLayout oldertest_heartrate_ll;
	private LinearLayout oldertest_bloodsuger_ll;
	private LinearLayout oldertest_ecg_ll;
	public Intent intent;
	// private boolean bleOn;// 蓝牙是否连接上
	private HealthApi mHealthApi;// health的api
	private Timer batteryQueryTimer;
	private String olderId;
	private String deviceMacAddress;
	private boolean isFamily;
	private RelativeLayout navrl;

	private static final int REQUEST_BLUETOOTH_DEVICE = 0;// 蓝牙连接
	private static final int REQUEST_OPEN_BT = 2;

	@Override
	public int getContentViewId() {
		return R.layout.activity_device_suifang_home;
	}

	@Override
	public void initSubViews(View view) {
		super.initSubViews(view);
		findView();
		controlView();

	}

	/**
	 * 初始化点击事件
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-25
	 */
	private void controlView() {
		oldertest_search_iv.setOnClickListener(new click());
		oldertest_bloodpress_ll.setOnClickListener(new click());
		oldertest_temperature_ll.setOnClickListener(new click());
		oldertest_bloodoxy_ll.setOnClickListener(new click());
		oldertest_heartrate_ll.setOnClickListener(new click());
		oldertest_bloodsuger_ll.setOnClickListener(new click());
		oldertest_ecg_ll.setOnClickListener(new click());
	}

	/**
	 * 初始化控件
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-25
	 */
	private void findView() {
		navrl = findViewById(R.id.activity_device_follow_navbar_rl);
		oldertest_search_iv = findViewById(R.id.oldertest_search_iv);
		oldertest_bloodpress_ll = findViewById(R.id.oldertest_bloodpress_ll);
		oldertest_temperature_ll = findViewById(R.id.oldertest_temperature_ll);
		oldertest_bloodoxy_ll = findViewById(R.id.oldertest_bloodoxy_ll);
		oldertest_heartrate_ll = findViewById(R.id.oldertest_heartrate_ll);
		oldertest_bloodsuger_ll = findViewById(R.id.oldertest_bloodsuger_ll);
		oldertest_ecg_ll = findViewById(R.id.oldertest_ecg_ll);
	}

	@Override
	public void initData() {
		super.initData();
		initHealth();
		olderId = getIntent().getStringExtra("olderId");
		deviceMacAddress = getIntent().getStringExtra("deviceMacAddress");
		isFamily = getIntent().getBooleanExtra("isFamily", false);
		if (isFamily) {
			navrl.setBackgroundResource(R.drawable.main_whiteyello_color_shape);
		}
		//
		// bleOn = true;
	}

	/**
	 * sdk的初始话
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-11
	 */
	private void initHealth() {
		mHealthApi = new HealthApi();
		mHealthApi.init(getApplicationContext(), new healthapicallback(),
				mbpHandler, mbtHandler, moxHandler, mbsHandler,
				new ecgcallback());
		mHealthApi.setBleCallBack(new blecallback());
		Log.e("version", HealthApi.getVersion());

	}

	/**
	 * 按钮点击事件 ClassName: click
	 * 
	 * @Description: TODO
	 * @author fzq
	 * @date 2017-10-10
	 */
	private class click implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.oldertest_search_iv:
				searchDevice();
				break;
			case R.id.oldertest_bloodpress_ll:
				intent = new Intent(SuiFangDeviceActivity.this,
						BloodPressMainActivity.class);
				intent.putExtra("olderId", olderId);
				intent.putExtra("isFamily", isFamily);
				intent.putExtra("deviceMacAddress", deviceMacAddress);
				intent.putExtra("bleOn", bleOn);
				startActivityForResult(intent,0x11);
				break;
			case R.id.oldertest_temperature_ll:
				intent = new Intent(SuiFangDeviceActivity.this,
						TemperatureTestActivity.class);
				intent.putExtra("olderId", olderId);
				intent.putExtra("isFamily", isFamily);
				intent.putExtra("bleOn", bleOn);
				intent.putExtra("deviceMacAddress", deviceMacAddress);
				startActivityForResult(intent,0x11);
				break;
			case R.id.oldertest_bloodoxy_ll:
				intent = new Intent(SuiFangDeviceActivity.this,
						BloodOxyMainActivity.class);
				intent.putExtra("olderId", olderId);
				intent.putExtra("isFamily", isFamily);
				intent.putExtra("bleOn", bleOn);
				intent.putExtra("deviceMacAddress", deviceMacAddress);
				startActivityForResult(intent,0x11);
				break;
			case R.id.oldertest_heartrate_ll:
				intent = new Intent(SuiFangDeviceActivity.this,
						HeartRateMainActivity.class);
				intent.putExtra("olderId", olderId);
				intent.putExtra("isFamily", isFamily);
				intent.putExtra("bleOn", bleOn);
				intent.putExtra("deviceMacAddress", deviceMacAddress);
				startActivityForResult(intent,0x11);
				break;
			case R.id.oldertest_bloodsuger_ll:
				// 无血糖试纸
				Toast.makeText(getApplicationContext(), "功能未开启",
						Toast.LENGTH_SHORT).show();
				break;
			case R.id.oldertest_ecg_ll:
				if (bleOn) {
					intent = new Intent(SuiFangDeviceActivity.this,
							ECGMainActivity.class);
					intent.putExtra("olderId", olderId);
					intent.putExtra("isFamily", isFamily);
					intent.putExtra("bleOn", bleOn);
					startActivityForResult(intent,0x11);
				} else {
					searchDevice();
				}
				break;
			}
		}
	}

	/**
	 * 搜索蓝牙设备
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	public void searchDevice() {
		if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			if (!bleOn) {// mState != BLE_DISCONNECTED
				Intent intent = new Intent(SuiFangDeviceActivity.this,
						FollowDeviceSearchActivity.class);
				if (deviceMacAddress != null && deviceMacAddress.length() > 4) {
				} else {
					ToastUtil.showMessage(getApplicationContext(),
							"请选择搜索到的随访仪设备");
				}
				intent.putExtra("deviceMacAddress", "" + deviceMacAddress);
				intent.putExtra("isFamily", isFamily);
				startActivityForResult(intent, REQUEST_BLUETOOTH_DEVICE);
			} else {
				// 断开设备蓝牙
				mHealthApi.bleDisconnect();
				bleOn = false;
				ToastUtil.showMessage(this, R.string.ble_is_un_relative);
			}
		} else {
			enableBluetooth();
		}
	}

	/**
	 * 打开手机蓝牙
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void enableBluetooth() {
		BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
		if (bta == null) {
			Toast.makeText(this, "不支持蓝牙", Toast.LENGTH_SHORT).show();
		} else {
			if (!bta.isEnabled()) {
				startActivityForResult(new Intent(
						"android.bluetooth.adapter.action.REQUEST_ENABLE"),
						REQUEST_OPEN_BT);
			}
		}
	}

	private class healthapicallback implements HealthApiCallBack {
		@Override
		public void healthCallBack(int type, Object data) {
		}
	}

	private class blecallback implements BleCallBack {
		@Override
		public void bleCallBack(int type, Object data) {
			if (type == HealthApi.BLE_STATUS) {
				setBleUiState((Integer) data);
			}
		}
	}

	private void modual_init() {
		mHealthApi.ecgQuery();
		mHealthApi.bsQuery();
		mHealthApi.batteryQuery();

		if (batteryQueryTimer == null)
			batteryQueryTimer = new Timer();
		batteryQueryTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				mHealthApi.batteryQuery();
			}
		}, 300000, 300000);
	}

	private void setBleUiState(int mState) {
		switch (mState) {
		case OnBLEService.BLE_CONNECTED:
			break;
		case OnBLEService.BLE_DISCONNECTED:
			break;
		case OnBLEService.BLE_NOTIFICATION_ENABLED:
			modual_init();
			break;
		case OnBLEService.BLE_NOTIFICATION_NOTENABLED:
			break;
		default:
			break;
		}
	}

	private class ecgcallback implements EcgCallBack {
		@Override
		public void onReceive(int[] data) {
		}
	}

	/**
	 * 温度测量
	 */
	private Handler mbtHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler moxHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mbpHandler = new Handler() {
		public void handleMessage(Message msg) {
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler mbsHandler = new Handler() {
		public void handleMessage(Message msg) {
		}
	};
	private boolean bleOn;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		disconect();
		if (mHealthApi != null)
			if (batteryQueryTimer != null)
				batteryQueryTimer.cancel();
		batteryQueryTimer = null;
	}

	private void disconect() {
		if (mHealthApi != null)
			if (bleOn) {
				mHealthApi.bleDisconnect();
			}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_BLUETOOTH_DEVICE:
			if (resultCode == RESULT_OK) {
				String strAddress = data.getExtras().getString(
						BluetoothDevice.EXTRA_DEVICE);
				bleOn = true;
				if (!mHealthApi.bleConnect(strAddress)) {
					Log.e("fzq", "connect error");
					bleOn = false;
				} else {
//					mySyntherizer.speak("随访仪连接成功");
				}
			} else {
			}
			break;

		case REQUEST_OPEN_BT:
			if (resultCode == RESULT_OK) {
			} else {
			}
			break;
		case 0x11:
			bleOn = data.getBooleanExtra("bleOn", false);
			break;
		}
	}

	@Override
	protected SuiFangDevicePresenter getPresenter() {
		return new SuiFangDevicePresenter(this);
	}

}
